//
//  NetRequest.m
//  NetRequesProject
//
//  Created by 蓓蕾 on 2021/9/6.
//

#import "NetRequest.h"
#import <AFNetworking.h>

@implementation NetRequest

+ (void)GetWithUrlString:(NSString *)URLString
              parameters:(nullable id)parameters
                 success:(nullable void (^)(id _Nullable responseObject))success
                 failure:(nullable void (^)(NSError *error))failure
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 30.0f;
    NSLog(@"数据请求网址：%@",URLString);
    NSLog(@"请求参数：%@",parameters);
    
    [manager GET:URLString parameters:parameters headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (success) {
            id jsons = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers  error:nil];
            success(jsons);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
#ifdef DEBUG
        NSLog(@"请求失败    开始");
        NSLog(@"=================       数据请求失败开始       ================");
        NSLog(@"                        请求方式 GET 请求                        ");
        NSLog(@"请求地址：%@",URLString);
        NSLog(@"请求参数：%@",parameters);
        NSLog(@"错误信息");
        NSLog(@"error = %@",error.localizedDescription);
        NSLog(@"=================       数据请求失败结束       ================");
        NSLog(@"请求失败    结束");
#else
#endif
    }];
}

+ (void)PostWithUrlString:(NSString *)URLString
               parameters:(nullable id)parameters
                  success:(nullable void (^)(id _Nullable responseObject))success
                  failure:(nullable void (^)(NSError *error))failure
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.requestSerializer.timeoutInterval = 30.0f;
    NSLog(@"数据请求网址：%@",URLString);
    NSLog(@"请求参数：%@",parameters);
    [manager POST:URLString parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            id jsons = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers  error:nil];
            success(jsons);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
        
        
#ifdef DEBUG
        NSLog(@"请求失败    开始");
        NSLog(@"=================       数据请求失败开始       ================");
        NSLog(@"                        请求方式 POST 请求                        ");
        NSLog(@"请求地址：%@",URLString);
        NSLog(@"请求参数：%@",parameters);
        NSLog(@"错误信息");
        NSLog(@"error = %@",error.localizedDescription);
        NSLog(@"=================       数据请求失败结束       ================");
        NSLog(@"请求失败    结束");
#else
#endif
        
    }];
}

+ (void)POSTWithFormData:(NSString *)url params:(nullable id)params successBlock:(nullable void (^)(id _Nullable responseObject))successBlock failureBlock:(nullable void (^)(NSError *error))failureBlock
{
    NSString *urlString = [NSString stringWithFormat:@"%@",url];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    manager.securityPolicy.allowInvalidCertificates = YES;
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {} error:nil];
    NSURLSessionUploadTask *task;
    task = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {}completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error)
        {
            if(failureBlock)
            {
                
                failureBlock(error);
            }
        }
        else
        {
            if(successBlock){
                successBlock(responseObject);
            }
        }
    }];
    [task resume];
}

+ (void)POSTWithBodyRow:(NSString *)URLString parameters:(nullable id)parameters showLog:(BOOL)showLog logTitle:(nullable NSString *)title success:(nullable void (^)(id _Nullable responseObject))success failure:(nullable void (^)(NSError *error))failure
{
//    URLString = [NSString stringWithFormat:@"%@/%@",BaseUrl,URLString];
    NSData *JSONdata = nil;
    if(parameters)
    {
        JSONdata = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil];
    }
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:nil error:nil];
    request.timeoutInterval= 30.0f;
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    request.cachePolicy = NSURLRequestReloadIgnoringCacheData; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    // 设置body
    [request setHTTPBody:JSONdata]; manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects: @"application/json", @"text/html", @"text/json", @"text/plain", @"text/javascript", nil];
    NSURLSessionDataTask *task = nil;
    task = [manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
        if(error)
        {
            if(failure){
                failure(error);
            }
            
            
#ifdef DEBUG
            NSLog(@"请求失败    开始");
            NSLog(@"=================       数据请求失败开始       ================");
            NSLog(@"                        请求方式 POST 请求                        ");
            NSLog(@"请求地址：%@",URLString);
            NSLog(@"请求参数：%@",parameters);
            [self logRequestPort:URLString withParama:parameters];
            NSLog(@"错误信息");
            NSLog(@"error = %@",error.localizedDescription);
            NSLog(@"=================       数据请求失败结束       ================");
            NSLog(@"请求失败    结束");
#else
#endif
            
        }else{
            
#ifdef DEBUG
            if (showLog) {
                NSLog(@"=================       数据请求开始       ================");
                NSLog(@"                        请求方式 POST 请求                        ");
                NSLog(@"数据请求网址：%@",URLString);
                NSLog(@"请求参数：%@",parameters);
                [self logRequestPort:URLString withParama:parameters];
                NSString *logTitle = title.length > 0 ? title : @"responseObject";
                NSLog(@"%@:%@",logTitle,responseObject);
                NSLog(@"=================       数据请求结束       ================");
            }
#else
#endif
            
            
            if(success){
                success(responseObject);
            }
        }
    }];
    [task resume];
}

+ (void)GETWithBodyRow:(NSString *)URLString parameters:(nullable id)parameters showLog:(BOOL)showLog logTitle:(nullable NSString *)title success:(nullable void (^)(id _Nullable responseObject))success failure:(nullable void (^)(NSError *error))failure
{
//    URLString = [NSString stringWithFormat:@"%@/%@",BaseUrl,URLString];
    NSData *JSONdata = nil;
    if(parameters)
    {
        JSONdata = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil];
    }
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:nil error:nil];
    request.timeoutInterval= 30.0f;
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    request.cachePolicy = NSURLRequestReloadIgnoringCacheData; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    // 设置body
    [request setHTTPBody:JSONdata]; manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects: @"application/json", @"text/html", @"text/json", @"text/plain", @"text/javascript", nil];
    NSURLSessionDataTask *task = nil;
    task = [manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
        if(error)
        {
            if(failure){
                failure(error);
            }
            
            
#ifdef DEBUG
            NSLog(@"请求失败    开始");
            NSLog(@"=================       数据请求失败开始       ================");
            NSLog(@"                        请求方式 POST 请求                        ");
            NSLog(@"请求地址：%@",URLString);
            NSLog(@"请求参数：%@",parameters);
            [self logRequestPort:URLString withParama:parameters];
            NSLog(@"错误信息");
            NSLog(@"error = %@",error.localizedDescription);
            NSLog(@"=================       数据请求失败结束       ================");
            NSLog(@"请求失败    结束");
#else
#endif
            
        }else{
            
#ifdef DEBUG
            if (showLog) {
                NSLog(@"=================       数据请求开始       ================");
                NSLog(@"                        请求方式 POST 请求                        ");
                NSLog(@"数据请求网址：%@",URLString);
                NSLog(@"请求参数：%@",parameters);
                [self logRequestPort:URLString withParama:parameters];
                NSString *logTitle = title.length > 0 ? title : @"responseObject";
                NSLog(@"%@:%@",logTitle,responseObject);
                NSLog(@"=================       数据请求结束       ================");
            }
#else
#endif
            
            
            if(success){
                success(responseObject);
            }
        }
    }];
    [task resume];
}

#pragma mark - 请求数据打印
+(void)logRequestPort:(NSString *)url withParama:(id)parameters
{
    if ([parameters isKindOfClass:[NSDictionary class]]) {
        NSDictionary *parama = (NSDictionary *)parameters;
        if (parama.count > 0) {
            NSMutableString *paramaString = [NSMutableString new];
            NSArray *keys = [parama allKeys];
            for (NSString *key in keys) {
                NSString *value = parama[key];
                [paramaString appendFormat:@"%@=%@&",key,value];
            }
            if (paramaString.length > 0) {
                [paramaString deleteCharactersInRange:NSMakeRange(paramaString.length - 1, 1)];
            }
            NSString *requestPort = [NSString stringWithFormat:@"%@?%@",url,paramaString];
            NSLog(@"请求详细地址");
            NSLog(@"requestPort = %@",requestPort);
        }
    }
}

@end
